package com.bafa.services;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.bafa.dbcache.LeagueCache;
import com.bafa.debug.Debug;
import com.bafa.jdbc.DBAccess;
import com.bafa.jdbc.QueryObject;
import com.bafa.jdbc.UpdateObject;
import com.bafa.tables.Keys;
import com.bafa.util.PasswordUtil;

public class UserServices {

	
	public static void changePassword(String userId, String oldPassword, String newPassword){
		DBAccess db = new DBAccess();
		QueryObject query = new QueryObject("users");
		query.addWhereAndField("ID","'"+userId+"'");
		query.addWhereAndField("Password","'"+PasswordUtil.encrypt(oldPassword)+"'");
		UpdateObject update = new UpdateObject();
		update.addField("Password",PasswordUtil.encrypt(newPassword));
		update.addField("resetpassword",0);
		try{
			ResultSet rs = db.query(query);
			if(rs.next()){
				
				db.update(query,update);
			}else{
				query.setQueryString("");
				query.addWhereAndField("Password","'"+oldPassword+"'");
				query.addWhereAndField("ID","'"+userId+"'");
				rs = db.query(query);
				if(rs.next()){
					db.update(query,update);
				}else{
					
				}
			}
			
		}catch(Exception e){
			Debug.printStackTrace(e);
			
		}finally{
			db.disconnect();
		}
		
	}
	
	public static void resetPassword(int teamId){
		DBAccess db = new DBAccess();
		QueryObject query = new QueryObject("users");
		query.addWhereAndField("TeamID",""+teamId);
		UpdateObject update = new UpdateObject();
		update.addField("Password",PasswordUtil.encrypt("password"));
		update.addField("ResetPassword",1);
		try{
			ResultSet rs = db.query(query);
			if(rs.next()){
				db.update(query,update);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.disconnect();
		}
	}
	public static void main(String[] args) {
		new UserServices().changePassword("artists","artists","artists");
	}

	static void addUser(int teamId,String user, String password, String rights, DBAccess db, String name)throws SQLException{
		
		
		QueryObject queryUsers = new QueryObject("users");
		UpdateObject update = new UpdateObject();
		update.addField("ID",user);
		update.addField("Password",PasswordUtil.encrypt(password));
		update.addField("Rights",rights);
		update.addField("TeamID", new Integer(teamId));
		update.addField("ResetPassword", 1);
		db.insert(queryUsers,update);
	}
}
